package com.choudou5.solr.web.handler.sys;

import com.choudou5.solr.annotation.ReqMapping;
import com.choudou5.solr.annotation.ReqMethod;
import com.choudou5.solr.framework.bean.UserBean;
import com.choudou5.solr.bean.common.PageResult;
import com.choudou5.solr.bean.common.SqlQueryBean;
import com.choudou5.solr.framework.constants.ErrorResp;
import com.choudou5.solr.framework.constants.UserConsts;
import com.choudou5.solr.framework.util.PageJumpUtil;
import com.choudou5.solr.framework.util.RequestUtil;
import com.choudou5.solr.utils.SqlQueryBuilder;
import com.choudou5.solr.web.handler.BaseHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Name：用户处理器
 * @Author：choudou5
 * @Date：2018-07-14
 */
public class UserHandler extends BaseHandler {

    @Override
    public void execute(String method, HttpServletRequest req, HttpServletResponse resp) {
        logger.info("UserHandler method:{}", method);
        switch (method){
            case "pageList":
                pageList(req, resp);
                break;
            case "setStatus":
                setStatus(req, resp);
                break;
            default:
                PageJumpUtil.errorOut(ErrorResp.Not_Found, req, resp);
                break;
        }
    }

    /**
     * 分页列表
     * @param req
     * @param resp
     */
    private void pageList(HttpServletRequest req, HttpServletResponse resp){
        SqlQueryBean sqlQueryBean = SqlQueryBuilder.buildWhereSql(req);
        PageResult<UserBean> pageResult = sysUserService.findPage(sqlQueryBean);
        req.setAttribute("pageResult", pageResult);
        PageJumpUtil.forward("userList", req, resp);
    }


    @ReqMapping(desc = "设置状态", method = ReqMethod.POST)
    private void setStatus(HttpServletRequest req, HttpServletResponse resp){
        if(isAdmin(req, resp)) {
            Integer userId = RequestUtil.getIntParameter(req, "userId");
            String status = RequestUtil.getStrParameter(req, "status");
            String reason = RequestUtil.getStrParameter(req, "reason");
            UserConsts.UserStatus userStatus = UserConsts.UserStatus.get(status);
            boolean valid = validParam(req, resp, new Object[]{userId, status, reason}, new String[]{"用户ID", "状态", "理由"});
            if(valid){
                sysUserService.updateStatus(userId, userStatus, reason);
                PageJumpUtil.writeJsonOk("设置成功", resp);
            }
        }
    }

}
